﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Utility;

namespace api
{
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 发生异常时
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            LogHelper.Error($"[全局异常]在响应 {context.HttpContext.Request.Path} 时出现异常，信息：{context.Exception.Message}");
            if (!context.ExceptionHandled)        //异常未被处理
            {
                if (this.IsAjaxRequest(context.HttpContext.Request) || true)//ajax请求
                {
                    context.Result = new JsonResult(new { code = -2 });//中断式---请求到这里结束了，不再继续Action
                }
                //else
                //{
                //    var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
                //    result.ViewData = new ViewDataDictionary(_modelMetadataProvider,
                //                                                context.ModelState);
                //    result.ViewData.Add("Exception", context.Exception.Message);
                //    context.Result = result;
                //}
                context.ExceptionHandled = true;//异常已被处理
            }
        }

        private bool IsAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header);
        }
    }
}
